package com.zhou.util.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lang.zhou
 * @date 2019/12/12
 */
public class HttpUtil {

    private static final String DEFAULT_CHARSET = "UTF-8";
    /**
     * http get请求
     * @param url 请求地址
     * @param headers 请求头
     * @param param 请求参数
     */
    public static String get(String url,Map<String, String> headers,Map<String, String> param) throws Exception{
        return get(url, headers, param,DEFAULT_CHARSET);
    }
    public static String get(String url,Map<String, String> headers,Map<String, String> param, String charset) throws Exception{
        HttpClient client = new DefaultHttpClient();
        // 实例化HTTP方法
        HttpGet get = new HttpGet();
        get.setHeader("accept", "*/*");
        get.setHeader("connection", "Keep-Alive");
        get.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        if(headers != null && headers.size() > 0){
            for(String key : headers.keySet()) {
                get.setHeader(key,headers.get(key));
            }
        }
        StringBuilder paramStr = new StringBuilder();
        if(param != null && param.size() > 0){
            if(!url.contains("?")){
                url += "?";
            }else{
                if(!url.endsWith("&")){
                    url += "&";
                }
            }
            for(String key : param.keySet()) {
                if(paramStr.length() > 0){
                    paramStr.append("&");
                }
                paramStr.append(key).append("=").append(param.get(key));
            }
        }
        url += paramStr.toString();
        String result ="";
        get.setURI(new URI(url));
        HttpResponse response = client.execute(get);
        result = entityToString(response.getEntity(),charset);
        /*try {
            result=new String(result.getBytes("ISO-8859-1"),"utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        return result;
    }
    /**
     * http get请求
     * @param url 请求地址
     * @param headers 请求头
     * @param param 请求参数
     */
    public static String post(String url,Map<String, String> headers,Map<String, String> param, String charset) throws Exception{
        HttpEntity entity = getPostEntity(url, headers, param);
        if(entity != null){
            return entityToString(entity,charset);
        }
        return null;
    }
    /**
     * http post请求
     * @param url 请求地址
     * @param headers 请求头
     * @param param 请求参数
     * @return  HttpEntity  使用org.apache.http.util.EntityUtils.toString()、com.alibaba.fastjson.JSON.parseObject()解析
     */
    public static HttpEntity getPostEntity(String url, Map<String, String> headers, Map<String, String> param) throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        if(headers != null && headers.size() > 0){
            for(String key : headers.keySet()) {
                post.setHeader(key, headers.get(key));
            }
        }


        post.setEntity(new UrlEncodedFormEntity(getTemplateParam(param),"utf-8"));
        HttpResponse execute = client.execute(post);
        HttpEntity entity = execute.getEntity();
        return entity;
    }
    private static List<NameValuePair> getTemplateParam(Map<String,String> map){
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for(Map.Entry<String,String> entry : map.entrySet()){
            pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        return pairs;
    }
    private static String entityToString(HttpEntity entity,String charset) throws IOException {
        String result = null;
        if(entity != null)
        {
            long length = entity.getContentLength();
            if(length != -1 && length < 2048)
            {
                result = EntityUtils.toString(entity,"UTF-8");
            }else {
                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), charset);
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l;
                while((l = reader1.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        Map<String,String> param = new HashMap<>();
        String a = HttpUtil.get("http://sinitekwh.3322.org:7080/si_er/framework/ueditor/third-party/codemirror/codemirror.js",
                null,null);
        param.put("clazz","com.sinitek.sirm.web.routine.ReceiveMessageAction");
        param.put("methodName","getTableSize");
        String b = HttpUtil.get("http://www.baidu.com",
                null,param);
        System.out.println();
    }
}
